package com.hh.TreeQuestions;

/**
 * @Author hanghao
 * @Date 2023/7/18 18:26
 * @Version 1.0
 * 二叉树的最近公共祖先
 * middle
 */

public class No236 {
    public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
        if(root == null || root == p || root == q) {
            return root;
        }
        TreeNode left = lowestCommonAncestor(root.left, p, q);
        TreeNode right = lowestCommonAncestor(root.right, p, q);
        if (left == null && right == null) {
            return null;
        } else if(left != null && right == null) {
            return left;
        } else if (right != null && left == null) {
            return right;
        } else {//left 和 right 都不为null
            return root;
        }
    }
}
